/**
 * @file form reducer
 * @author liaoxuezhi@baidu.com
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import {
  REQ_FETCH_WIZARD,
  REC_FETCH_WIZARD,

  REQ_FETCH_STEP,
  REC_FETCH_STEP,

  REQ_SAVE_STEP,
  REC_SAVE_STEP,

  REQ_SAVE_WIZARD,
  REC_SAVE_WIZARD,

  UPDATE_STEP,
  RESET_WIZARD,
  REQ_ACTION_WIZARD,
  REC_ACTION_WIZARD
} from './action-types';
import {handleActions} from 'redux-actions';
import * as update from 'react-addons-update';
import {compose, createRequestReducer, createReceiveReducer} from '../renderer';
import {merge} from '../../util/helper';


export default handleActions({

  // 获取数据相关
  [REQ_FETCH_WIZARD]: createRequestReducer(),
  [REC_FETCH_WIZARD]: compose((state, action) => action.error ? state : update(state, {
    data: {
      [state.data ? '$merge' : '$set']: action.payload.data || null
    }
  }), createReceiveReducer()),

  // 保存数据相关
  [REQ_SAVE_WIZARD]: createRequestReducer('saving'),
  [REC_SAVE_WIZARD]: compose((state, action) => action.error ? state : update(state, {
    data: {
      [state.data ? '$merge' : '$set']: action.payload.data || null
    }
  }), createReceiveReducer('saving')),


  // 获取数据相关
  [REQ_FETCH_STEP]: createRequestReducer(),
  [REC_FETCH_STEP]: compose((state, action) => action.error ? state : update(state, {
    data: {
      [state.data ? '$merge' : '$set']: action.payload.data || null
    }
  }), createReceiveReducer()),

  // 保存数据相关
  [REQ_SAVE_STEP]: compose((state, action) => update(state, {
    data: {
      [state.data ? '$merge' : '$set']: action.payload
    }
  }), createRequestReducer('saving')),
  [REC_SAVE_STEP]: compose((state, action) => action.error ? state : update(state, {
    data: {
      [state.data ? '$merge' : '$set']: action.payload.data || null
    }
  }), createReceiveReducer('saving')),

  [UPDATE_STEP]: (state, action) => update(state, {
    data: {
      [state.data ? '$merge' : '$set']: action.payload
    }
  }),

  // 其他 action 操作
  [REQ_ACTION_WIZARD]: createRequestReducer('saving', 'action'),
  [REC_ACTION_WIZARD]: createReceiveReducer('saving', 'action'),

  [RESET_WIZARD]: (state, action) => update(state, {
    data: {
      $set: {}
    }
  })
}, {
  ctx: null,
  message: null,
  error: null,
  invalid: false,
  fetching: false,
  saving: false,
  data: {},

  // 其他 ajax 操作时, 记录状态
  action: {
    ctx: null,
    message: null,
    saving: false,
    invalid: false,
    error: null
  }
});
